<template>
	<view class="content">
		<view class="content-top">
			<view class="u-flex">
				<view class="text" style="flex: 0 0 130rpx;">车牌号：</view>
				<u--input
					placeholder="请输入车牌号"
					maxlength="8"
					border="surround"
					fontSize="32rpx"
					v-model="carNumber"></u--input>
				<view class="u-flex u-align-center u-m-l-30">
					<view class="u-m-r-20">价税分离</view>
					<u-switch
						v-model="priceTaxSplit" 
						@change="changeSplit" 
						activeColor="#005aba"></u-switch>
				</view>
			</view>
			<view class="u-flex u-m-t-30" style="position: relative;">
				<view class="text" style="flex: 0 0 130rpx;">日期：</view>
				<u--input
					placeholder="请录入日期(如:0102、1.2)"
					border="surround"
					fontSize="32rpx"
					maxlength="5"
					v-model="date"
					@change="changeHanderDate"
					@blur="blurDate"></u--input>
				<!-- <view class="tips">
					格式如：0102、01.02、01-02、01/02
				</view> -->
				<view class="u-m-l-30">
					<u-checkbox-group
					    v-model="checkDate"
					    placement="row"
						@change="changeDate">
						<u-checkbox
							checked
							activeColor="#005aba" 
							label="到期"
							name="到期"
							shape="circle"></u-checkbox>
					</u-checkbox-group>
				</view>
			</view>
		</view>
		<!-- 客户傻缺需求无法循环，凑合写吧 -->
		<view class="content-box">
			<view class="box boxTitle u-flex">
				<view class="item">
					<u-input
						border="none"
						inputAlign="center"
						fontSize="28rpx"
						readonly
						:customStyle="{height: '50rpx'}"
						value="交强"></u-input>
				</view>
				<view class="item">
					<u-input
						border="none"
						inputAlign="center"
						fontSize="28rpx"
						readonly
						:customStyle="{height: '50rpx'}"
						value="税"></u-input>
				</view>
				<view class="item">
					<u-input
						border="none"
						inputAlign="center"
						fontSize="28rpx"
						readonly
						:customStyle="{height: '50rpx'}"
						value="商业"></u-input>
				</view>
				<view class="item">
					<u-input
						border="none"
						inputAlign="center"
						fontSize="28rpx"
						readonly
						:customStyle="{height: '50rpx'}"
						value="驾乘"></u-input>
				</view>
			</view>
			<view class="box u-flex">
				<view class="item text u-text-center">保费</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder="交强保费"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="money.jq"
						@focus="onFocus('jq', 'money')"
						@change.native="onChangeMoney('jq', 'money')"
						@blur="onblurMoney('jq', 'money')"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder="税保费"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="money.tax"
						@focus="onFocus('tax', 'money')"
						@change.native="onChangeMoney('tax', 'money')"
						@blur="onblurMoney('tax', 'money')"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="money.business"
						@focus="onFocus('business', 'money')"
						@change.native="onChangeMoney('business', 'money')"
						@blur="onblurMoney('business', 'money')"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="money.drive"
						@focus="onFocus('drive', 'money')"
						@change.native="onChangeMoney('drive', 'money')"
						@blur="onblurMoney('drive', 'money')"></u-input>
				</view>
			</view>
			<view class="box u-flex">
				<view class="item text u-text-center">折扣</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="discount.jq"
						@focus="onFocus('jq', 'discount')"
						@change.native="onChangeMoney('jq', 'discount')"
						@blur="onblurMoney('jq', 'discount')"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="discount.tax"
						@focus="onFocus('tax', 'discount')"
						@change.native="onChangeMoney('tax', 'discount')"
						@blur="onblurMoney('tax', 'discount')"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="discount.business"
						@focus="onFocus('business', 'discount')"
						@change.native="onChangeMoney('business', 'discount')"
						@blur="onblurMoney('business', 'discount')"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						:customStyle="inputCustomStyle"
						v-model="discount.drive"
						@focus="onFocus('drive', 'discount')"
						@change.native="onChangeMoney('drive', 'discount')"
						@blur="onblurMoney('drive', 'discount')"></u-input>
				</view>
			</view>
			<view class="box u-flex">
				<view class="item text u-text-center">实付</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPayment.jq"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPayment.tax"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPayment.business"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPayment.drive"></u-input>
				</view>
			</view>
			<view class="box u-flex">
				<view class="item text u-text-center">优惠</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPrefer.jq"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPrefer.tax"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPrefer.business"></u-input>
				</view>
				<view class="item">
					<u-input
						type="digit"
						placeholder=" "
						:cursor="index"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="inputCustomStyle"
						v-model="newPrefer.drive"></u-input>
				</view>
			</view>
		</view>
		
		<view class="content-count">
			<view class="u-flex u-m-t-30">
				<view class="text">保费:</view>
				<view class="input">
					<u-input
						placeholder="保费合计"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="{marginLeft: '20rpx'}"
						v-model="moneyTotal"
					  ></u-input>
				</view>
				<view class="u-flex u-row-right u-flex-1 u-p-l-30">
					<view class="u-m-r-20">数值精确</view>
					<u-switch
						v-model="accurate" 
						@change="changeAccurate" 
						activeColor="#005aba"></u-switch>
				</view>
			</view>
			<view class="u-flex u-m-t-30">
				<view class="text">实付:</view>
				<view class="input">
					<u-input
						placeholder="实付合计"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="{marginLeft: '20rpx'}"
						v-model="paymentTotal"></u-input>
				</view>
				<view class="u-flex u-row-right u-flex-1 u-p-l-30">
					<u-button
						type="success" 
						:plain="true" 
						text="生成报价"
						:customStyle="{width: '200rpx',fontSize: '28rpx',borderRadius: '10rpx',margin: 0}"
						@click="onCopy"
					></u-button>
				</view>
			</view>
			<view class="u-flex u-m-t-30">
				<view class="text">优惠:</view>
				<view class="input">
					<u-input
						placeholder="优惠合计"
						border="surround"
						fontSize="28rpx"
						inputAlign="center"
						readonly
						:customStyle="{marginLeft: '20rpx'}"
						v-model="preferTotal"></u-input>
				</view>
				<view class="u-flex u-row-right u-flex-1 u-p-l-30">
					<u-button
						type="primary" 
						color="#005aba"
						:plain="true" 
						text="归零"
						:customStyle="{width: '200rpx',fontSize: '28rpx',borderRadius: '10rpx',margin: '0 0 0 30rpx'}"
						@click="onReset"
					></u-button>
				</view>
			</view>
		</view>
		
		<view class="image">
			<image style="width: 100%;" class="icon" :src="'https://upload.hzjruide.com/jisuanqi/tip_pic.jpg?' + datetime" mode="widthFix"></image>
		</view>
		
		<u-notify :message="message" ref="uNotify"></u-notify>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				showToast: false,
				message: '日期格式不正确',
				inputCustomStyle: {
					marginLeft: '20rpx',
					height: '50rpx',
					paddingLeft: '10rpx',
					paddingRight: '10rpx'
				},
				carNumber: '',
				priceTaxSplit: true,
				money: {
					title: '保费',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				},
				discount: {
					title: '折扣',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				},
				payment: {
					title: '实付',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				},
				prefer: {
					title: '优惠',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				},
				moneyTotal: 0,
				paymentTotal: 0,
				preferTotal: 0,
				accurate: false,
				showConModel: false,
				showDate: false,
				datetime: new Date(),
				date: '',
				newDate: [],
				checkDate: ['到期']
			}
		},
		onShow() {
			// 权限跳转
			// let date = new Date()
			// let year = date.getFullYear()
			// let month = (date.getMonth() + 1 < 10 ? '0'+ (date.getMonth() + 1) : date.getMonth() + 1)
			// let day = (date.getDate() < 10 ? '0'+ date.getDate() : date.getDate())
			// let d = year + '-' + month + '-' + day
			// if (d == '2024-01-27') {
			// 	uni.navigateTo({
			// 		url: '/pages/error/error'
			// 	})
			// }
		},
		computed: {
			newPayment() {
				let obj = {}
				for (let key in this.payment) {
					if (key !== 'title') {
						obj[key] = Math.floor((this.payment[key] || 0) * 100) / 100
					}
				}
				return obj
			},
			newPrefer() {
				let obj = {}
				for (let key in this.prefer) {
					if (key !== 'title') {
						obj[key] = Math.floor((this.prefer[key] || 0) * 100) / 100
					}
				}
				return obj
			}
		},
		watch: {
			money: {
				handler (val) {
					this.watchNumber(val)
				},
				deep: true
			},
			prefer: {
				handler (val) {
					this.watchNumber(val)
				},
				deep: true
			},
		},
		onReady() {
		},
		methods: {
			onlyNumOnePoint(number_only) {
				number_only = String(number_only)
				// 先把非数字的都替换掉，除了数字和小数点
				number_only = number_only.replace(/[^\d.]/g, '')
				// 必须保证第一个为数字而不是小数点   
				number_only = number_only.replace(/^\./g, '')
				// 保证只有出现一个小数点而没有多个小数点  
				number_only = number_only.replace(/\.{2,}/g, '.')
				// 第一位0开头，0后面为数字，则过滤掉，取后面的数字
				number_only = number_only.replace(/^0+(\d)/g, '$1')
				// 保证小数点只出现一次，而不能出现两次以上  
				number_only = number_only.replace('.','$#$').replace(/\./g, '').replace('$#$', '.')
				// 保证只能输入两个小数   
				number_only = number_only.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')
				return number_only
			},
			onChangeMoney(type, preType) {
				if (preType === 'money') {
					this.money[type] = this.onlyNumOnePoint(this.money[type])
				} else {
					this.discount[type] = this.onlyNumOnePoint(this.discount[type])
				}
				const money = Number(this.money[type] || 0)
				const discount = Number(this.discount[type] || 0)
				const num = (type !== 'tax' && this.priceTaxSplit) ? 1.06 : 1
				if (parseFloat(discount) === 0) {
					this.prefer[type] = 0
					this.payment[type] = money
				} else {
					this.prefer[type] = parseFloat(money / num * (discount || 1) / 100).toFixed(4)
					this.payment[type] = parseFloat(money - this.prefer[type]).toFixed(4)
				}
				if (preType === 'discount') {
					if (discount > 100) {
						this.$refs.uNotify.show({
							type: 'error',
							message: '折扣数值在0~100之间'
						})
					}
				}
			},
			onFocus(type, preType) {
				if (preType === 'money') {
					if (parseFloat(this.money[type]) === 0) {
						this.money[type] = ''
					}
				} else {
					if (parseFloat(this.discount[type]) === 0) {
						this.discount[type] = ''
					}
				}
			},
			onblurMoney(type, preType) {
				if (preType === 'money') {
					if (!this.money[type]) {
						this.money[type] = 0
					}
				} else {
					if (!this.discount[type]) {
						this.discount[type] = 0
					}
				}
			},
			// 四舍五入保留2位小数（若第二位小数为0，则保留一位小数）
			keepTwoDecimal (num) {
				if (isNaN(num)) num = 0
				var result = parseFloat(num)
				if (isNaN(result)) {
					return false
				}
				result = Math.round(num * 100)
				return result
			},
			watchNumber(val) {
				// 保费
				let m = 0
				for (let key in this.money) {
					if (key !== 'title') {
						m += parseFloat(this.money[key] || 0)
					}
				}
				// 实付
				let payment = 0
				for (let key in this.payment) {
					if (key !== 'title') {
						payment += parseFloat(this.payment[key] || 0) 
					}
				}
				// 优惠
				let prefer = 0
				for (let key in this.prefer) {
					if (key !== 'title') {
						prefer += parseFloat(this.prefer[key] || 0) 
					}
				}
				this.moneyTotal = Math.floor(m * 100) / 100 || 0
				
				if (this.accurate) {
					this.preferTotal = this.keepTwoDecimal(prefer / 100)
					this.paymentTotal = parseFloat(this.moneyTotal - this.preferTotal).toFixed(2)
				} else {
					// this.paymentTotal = parseFloat(payment).toFixed(2)
					// this.preferTotal = parseFloat(this.moneyTotal - this.paymentTotal).toFixed(2))
					this.preferTotal = Math.floor(prefer)
					this.paymentTotal = parseFloat(this.moneyTotal - this.preferTotal).toFixed(2)
				}
			},
			changeDate(data) {
				this.checkDate = data
			},
			// 数值精确
			changeAccurate() {
				this.watchNumber()
			},
			// 价税分离
			changeSplit() {
				this.onChangeMoney('jq', 'money')
				this.onChangeMoney('tax', 'money')
				this.onChangeMoney('business', 'money')
				this.onChangeMoney('drive', 'money')
				this.onChangeMoney('jq', 'discount')
				this.onChangeMoney('tax', 'discount')
				this.onChangeMoney('business', 'discount')
				this.onChangeMoney('drive', 'discount')
			},
			isDateValid(str) {
			    // 定义日期格式的正则表达式
			    // var dateRegex = /^\d{4}-\d{2}-\d{2}$/
			    let reg1 = /^\d{1,2}-\d{1,2}$/.test(str)
			    let reg2 = /^\d{1,2}\/\d{1,2}$/.test(str)
			    let reg3 = /^\d{1,2}.\d{1,2}$/.test(str)
			    let reg4 = /^\d{2}\d{2}$/.test(str)
			    
			    return reg1 || reg2 || reg3 || reg4
			},
			blurDate(data) {
				if (this.date) {
					if (!this.isDateValid(this.date)) {
						this.$refs.uNotify.show({
							type: 'error',
							message: '日期格式不正确'
						})
					}
				}
			},
			changeHanderDate() {
				let date = String(this.date)
				if (!date) return false
				let arr = []
				if (date.indexOf('.') !== -1) {
					arr = date.split('.')
				} else if (date.indexOf('-') !== -1) {
					arr = date.split('-')
				}  else if (date.indexOf('/') !== -1) {
					arr = date.split('/')
				} else {
					arr = [date.slice(0,2), date.slice(2)]
				}
				if (arr.length) {
					if (Number(arr[0]) > 12) {
						arr[0] = '12'
					}
					if (arr[1].length > 2 && Number(arr[1]) < 31) {
						arr[1] = '31'
					}
					if (Number(arr[1]) > 31) {
						arr[1] = '31'
					}
					this.newDate = arr
					this.$nextTick(() => {
						if (date.indexOf('.') !== -1) {
							this.date = arr.join('.')
						} else if (date.indexOf('-') !== -1) {
							this.date = arr.join('-')
						} else if (date.indexOf('/') !== -1) {
							this.date = arr.join('/')
						} else {
							this.date = arr.join('')
						}
					})
				}
			},
			// 复制
			onCopy() {
				let data = ``
				data += `尊敬的客户，您好！\n您的保险报价单如下：\n------------------------\n`
				data += `车牌号：${this.carNumber}\n`
				if (this.date) {
					data += `到期日期：${this.newDate[0] + '月' + this.newDate[1] + '日'}\n`
				} else {
					data += `到期日期：${this.checkDate[0]}\n`
				}
				data += `交强险：${this.money.jq}\n`
				if (this.money.tax) {
					data += `车船税：${this.money.tax}\n`
				}
				if (this.money.business) {
					data += `商业险：${this.money.business}\n`
				}
				if (this.money.drive) {
					data += `驾乘险：${this.money.drive}\n`
				}
				data += `合计：${this.moneyTotal}\n`
				data += `实付：${this.paymentTotal}\n`
				data += `优惠：${this.preferTotal}\n`
				data += `------------------------\n此报价仅当天有效，切勿跨夜支付，以免造成损失。\n`
				data += `折扣：${this.discount.jq}/${this.discount.tax}/${this.discount.business}/${this.discount.drive}`
				uni.setClipboardData({
					data: data,
					success(res) {
						uni.showToast({
							title: '复制成功',
							icon: 'none'
						})
					},
					fail(err) {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						})
					}
				})
			},
			// 归零
			onReset() {
				// Object.assign(this.$data, this.$options.data())
				this.carNumber = ''
				this.priceTaxSplit = true
				this.moneyTotal = 0
				this.paymentTotal = 0
				this.preferTotal = 0
				this.accurate = false
				this.date = ''
				this.newDate = []
				this.checkDate = ['到期']
				this.money = {
					title: '保费',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				}
				this.discount = {
					title: '折扣',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				}
				this.payment = {
					title: '实付',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				}
				this.prefer = {
					title: '优惠',
					jq: 0,
					tax: 0,
					business: 0,
					drive: 0
				}
			},
			// 选择日期
			formatter(type, value) {
				let newVal = ''
				// if (type === 'year') {
				// 	return `${value}年`
				// }
				if (type === 'month') {
					newVal += `${value}月`
				}
				if (type === 'day') {
					newVal += `${value}日`
				}
				return newVal
			},
			setTimestamp(timestamp) {
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = (date.getMonth() + 1 < 10 ? '0'+ (date.getMonth() + 1) : date.getMonth() + 1)
				const day = (date.getDate() < 10 ? '0'+ date.getDate() : date.getDate())
				const d = month + '月' + day + '日'
				this.showDate = false
				this.$nextTick(() => {
					this.date = d
				})
			},
			onConfirm(data) {
				this.setTimestamp(data.value)
			}
		}
	}
</script>

<style lang="scss" scoped>
	$width: 70rpx;
	.content {
		padding: 30rpx 30rpx 120rpx;
		::v-deep .u-picker__view .u-picker__view__column:first-child {
			position: fixed;
			z-index: -100;
			left: -10000px;
		}
		&-top {
			.text {
				font-size: 32rpx;
			}
		}
		&-box {
			margin-top: 20rpx;
			.text, .desc {
				width: $width;
				flex: 0 0 $width;
			}
			.item {
				margin-top: 20rpx;
			}
			.boxTitle {
				padding-left: $width;
			}
		}
		&-count {
			.text {
				width: $width;
			}
			.input {
				width: 350rpx;
			}
		}
	}
	.item {
		margin-top: 20rpx;
	}
	.image {
		margin-top: 40rpx;
	}
	.tips {
		color: #999;
		position: absolute;
		left: 130rpx;
		bottom: -46rpx;
	}
</style>
